package edu.hrbu.spring.controller;

import edu.hrbu.spring.pojo.Dept;
import edu.hrbu.spring.pojo.User;
import edu.hrbu.spring.service.DeptService;
import edu.hrbu.spring.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 徐登宇
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource(name = "userServiceImpl")
    UserService userService;

    @Resource(name = "deptServiceImpl")
    DeptService deptService;

    @RequestMapping("/list/{deptId}")
    public String list(Model model,
                       @PathVariable("deptId") Integer deptId) {
        List<User> userList = userService.getUsersByDeptId(deptId);
        model.addAttribute("userList", userList);
        model.addAttribute("deptId", deptId);
        return "user/list";
    }

    @RequestMapping("/to/save/{deptId}")
    public String toSave(Model model,
                         @PathVariable("deptId") Integer deptId) {
        model.addAttribute("deptId", deptId);
        return "user/add";
    }

    @RequestMapping("/save/{deptId}")
    public String save(User user,
                       @PathVariable("deptId") int deptId) {
//        System.out.println("@@@user=> " + user + "@@@" + deptId);
        userService.save(user, deptId);
        return "redirect:/user/list/" + deptId;
    }

    @RequestMapping("/info/{userId}/{deptId}")
    public String getInfo(Model model,
                          @PathVariable("userId") int userId,
                          @PathVariable("deptId") int deptId) {
        User user = userService.getInfo(userId);
        Dept dept = new Dept();
        dept.setDeptId(deptId);
        user.setDept(dept);

        List<Dept> deptList = deptService.getAllDept();
        model.addAttribute("user", user);
        model.addAttribute("deptList", deptList);

        System.out.println("@@@user@@@" + user);
        System.out.println("@@@deptList@@@" + deptList);
        return "user/info";
    }

    @RequestMapping("/edit")
    public String edit(@RequestParam("userId") int userId, @RequestParam("userName") String userName, @RequestParam("deptId") int deptId) {
//        System.out.println("@@@"+userName+deptId);
        userService.editNameAndDeptId(userId, userName, deptId);
        return "redirect:/user/list/" + deptId;
    }

}
